package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import com.baomidou.mybatisplus.extension.api.R;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Author: 🐱🐱🐱
 * @Date: 2025/8/20 15:26
 * @Description:
 **/
@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secreKey}")
    public String secreKey;

    @Value("${minio.bucketName}")
    public String bucketName;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{

        String url ="";
        //1.构建minio client
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpointUrl)
                .credentials(accessKey, secreKey)
                .build();
        //2.判断桶是否存在 不存在创建桶
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(b){
            System.out.println("bucketName is exist");
        }else {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //3.文件上传
        //3.1文件新的名字 当前的毫秒值+随机uuid的字符串
       String fileName = System.currentTimeMillis()+UUID.randomUUID().toString();

        //3.2文件上传
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(),file.getSize(),-1)
                        .contentType(file.getContentType())
                        .build()
        );
        //4.构建文件的完整地址
        url = endpointUrl +"/" +bucketName +"/" +fileName;
        //5.返回文件地址
        return Result.ok(url);
    }

}
